import React from 'react';
import ErrorChild from './ErrorChild';

export default class ErrorBoundary extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  /* 获取子组件中的错误 */
  static getDerivedStateFromError(error) {
    console.log('error Boundary', error);
    // 更新 state 使下一次渲染能够显示降级后的 UI
    return { hasError: true };
  }
  componentDidCatch(error, errorInfo) {
    // 获取错误信息做相对应的操作
    console.group('componentDidCatch Boundary ===>');
    console.log('Boundary error', error);
    console.log('Boundary errorInfo', errorInfo);
    console.groupEnd();
  }

  render() {
    console.log(this.state.hasError, '===========>');
    if (this.state.hasError) return <h1>Something went wrong.</h1>;
    return (
      <div>
        <h2>Error Boundary 避免白屏</h2>
        <ErrorChild />
      </div>
    );
  }
}
